package ws

import (
	"svr/src/logs"
	"svr/src/msg"
	"svr/src/xutil"
	"time"

	"google.golang.org/protobuf/proto"
)

var mapHander *xutil.Map

type HAND_FUNC func(mr proto.Message, task *MsgTask) *msg.Error

type HandlerInfo struct {
	MsgR proto.Message
	Func HAND_FUNC
}

func init() {
}
func GetMessageName(m proto.Message) string {
	return string(proto.MessageName(m).Name())
}
func AddHandler(mr proto.Message, handler HAND_FUNC) {
	if mapHander == nil {
		mapHander = xutil.CreateMap()
	}
	name := GetMessageName(mr)
	if mapHander.ContainsKey(name) {
		logs.Errorf("Msg Name:%s is Regisiter.", name)
		return
	}
	logs.Debugf("name::%+v,func:%+v", name, handler)

	mapHander.Set(name, &HandlerInfo{
		MsgR: mr,
		Func: handler,
	})
}

func runTask(task *MsgTask) {
	cfg := task.Msg.Conf
	name := cfg.Name
	v := mapHander.Get(name)
	// logs.Debugf("name:%+v", name, v)
	if v != nil {
		hi := v.(*HandlerInfo)
		m := proto.Clone(hi.MsgR)
		err := proto.Unmarshal(task.Msg.Data, m)
		if err != nil {
			logs.Errorf("msg name:%s Unmarshal error", name)
			return
		}
		task.MsgR = m
		tmNow := time.Now()
		task.StartTime = tmNow
		task.Dev.TimeOutStamp = tmNow.Add(DurHeartTimeout)
		mer := hi.Func(m, task)
		if mer != nil {
			logs.Errorf("msg name:%s handler error!!!", name)
			return
		}

	} else {
		logs.Errorf("msg name:%s is not Regisiter", name)
	}
}
